// pages/loan-apply/loan-apply.js
const api = require('../../utils/api.js')
const subscribe = require('../../utils/subscribe.js')
const app = getApp()

Page({
    data: {
        assetId: '',
        assetName: '',
        assetCode: '',
        purpose: '',
        expectedReturnDate: '',
        minDate: '',
        submitting: false
    },

    onLoad(options) {
        const { assetId, assetName, assetCode } = options
        const today = new Date()
        const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
        const minDate = tomorrow.toISOString().split('T')[0]

        this.setData({
            assetId,
            assetName: decodeURIComponent(assetName || ''),
            assetCode: decodeURIComponent(assetCode || ''),
            minDate
        })
    },

    onPurposeInput(e) {
        this.setData({ purpose: e.detail.value })
    },

    onDateChange(e) {
        this.setData({ expectedReturnDate: e.detail.value })
    },

    async submitApplication() {
        const { assetId, purpose, expectedReturnDate } = this.data

        if (!purpose) {
            wx.showToast({ title: '请填写借用目的', icon: 'none' })
            return
        }
        if (!expectedReturnDate) {
            wx.showToast({ title: '请选择归还日期', icon: 'none' })
            return
        }

        // 请求订阅消息授权（使用动态模板ID）
        try {
            await subscribe.requestLoanSubscribe()
        } catch (err) {
            console.log('用户拒绝订阅消息', err)
            // 继续执行，不强制要求订阅
        }

        this.setData({ submitting: true })

        try {
            await api.request({
                url: '/asset/loan/apply',
                method: 'POST',
                data: {
                    assetId,
                    purpose,
                    expectedReturnDate,
                    openid: app.globalData.openid,
                    userInfo: app.globalData.userInfo
                }
            })

            wx.showToast({ title: '申请成功', icon: 'success' })

            setTimeout(() => {
                wx.navigateBack()
            }, 1500)
        } catch (error) {
            console.error('申请失败:', error)
            wx.showToast({ title: '申请失败，请重试', icon: 'none' })
            this.setData({ submitting: false })
        }
    }
})
